package com.demo.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.aop.AuthorizationRequired;
import com.demo.core.constants.HttpStatus;
import com.demo.core.domain.Result;
import com.demo.core.exception.ParameterException;
import com.demo.domain.TeamComposition;
import com.demo.domain.TeamProfile;
import com.demo.domain.ro.TeamProfileRequest;
import com.demo.service.TeamProfileService;
import com.demo.utils.PageBean;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/teamProfile")
public class TeamProfileController {
    @Autowired
    TeamProfileService teamProfileService;




    /**
     * 得到队伍详情
     *
     * @param tpId
     * @param request
     * @return
     * @throws ParameterException
     */
    @AuthorizationRequired
    @PostMapping("/getOneTeamProfile")
    public Result getTeamProfileById(Long tpId, HttpServletRequest request) throws ParameterException {
        if (tpId == null || tpId < 0l) {
            throw new ParameterException("tpId为空");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        TeamProfile teamProfile = teamProfileService.getTeamProfileById(tpId, uid);
        return teamProfile != null ?
                Result.success(HttpStatus.SUCCESS, "查找成功", teamProfile) :
                Result.success(HttpStatus.BAD_REQUEST, "无相关信息", null);
    }

    /**
     * 按关键词搜索队伍(未满人、未截止的优先呈现)
     *
     * @param teamProfileRequest
     * @return
     */
    @AuthorizationRequired
    @Operation(summary = "搜索队伍")
    @PostMapping("/getTeamProfileByKW")
    public Result getTeamProfileByKW(@RequestBody TeamProfileRequest teamProfileRequest, HttpServletRequest request) throws ParameterException, Exception {
        if (teamProfileRequest.current == 0 || teamProfileRequest.size == 0) {
            throw new ParameterException("分页参数无效");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        teamProfileRequest.setUid(uid);
//        得到搜索结果
        IPage<TeamProfile> page = teamProfileService.getTeamByConditions(teamProfileRequest);
        int succeed = 0;
//            存储分页信息
        succeed = page != null && page.getRecords().size() > 0 ? 1 : 0;
        return succeed > 0 ? Result.success(HttpStatus.SUCCESS, "查找成功", page) :
                Result.success(HttpStatus.SUCCESS, "无相关信息", new Page<>());
    }

    /**
     * 得到uid参与的所有队伍
     *
     * @param request
     * @return
     * @throws Exception
     */
    @AuthorizationRequired
    @Operation(summary = "获取某人参加的所有队伍的队伍信息")
    @PostMapping("/getTeamsByUid")
    public Result getAllTeamsByUid(HttpServletRequest request) throws Exception {
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        if (uid != null) {
            List<TeamProfile> list = teamProfileService.getInTeam(uid);
            if (list != null && list.size() > 0) {
                return Result.success(HttpStatus.SUCCESS, "查找成功", list);
            }
        }
        return Result.success(HttpStatus.NOT_LOGIN, "无相关信息", null);
    }

    /**
     * 组建队伍(插入新纪录)
     *
     * @param teamProfile
     * @param request
     * @return
     */
    @AuthorizationRequired
    @Operation(summary = "发布招募（组建队伍）"
            , description = "只填写队伍的基本信息，默认当前发布成员为该队伍队长（该接口不含队伍成员的增删改）")
    @PostMapping("/organizeTeam")
    public Result organizeTeam(@RequestBody TeamProfile teamProfile, HttpServletRequest request) throws ParameterException, Exception {
        if (teamProfile == null || request == null) {
            throw new ParameterException("teamProfile或request为null");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        String msg = teamProfileService.organizeTeam(teamProfile, uid);
        return Result.success(HttpStatus.SUCCESS, msg, null);
    }

    /**
     * 修改队伍基本信息(根据队伍id)
     *
     * @param teamProfile
     * @return
     */
    @AuthorizationRequired
    @Operation(summary = "修改队伍基本信息", description = "不包括成员信息，只有队长喝指导老师可改")
    @PostMapping("/modifyTeamMsg")
    public Result modifyTeamMsg(@RequestBody TeamProfile teamProfile, HttpServletRequest request) throws ParameterException, Exception {
        if (teamProfile == null) {
            throw new ParameterException("teamProfile为null");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
//        得到当前用户的uid
        Long uid = (Long) request.getAttribute("userId");
        if (uid != null && uid > 0l) {
            String msg = teamProfileService.modifyTeamMsg(teamProfile, uid);
            return Result.success(HttpStatus.SUCCESS, msg, null);
        }
        return Result.success(HttpStatus.BAD_REQUEST, "无当前用户的该队伍信息", null);
    }

    /**
     * 解散队伍
     *
     * @param tpId
     * @param request
     * @return
     * @throws ParameterException
     */
    @AuthorizationRequired
    @Operation(summary = "解散队伍", description = "只有队长喝指导老师可改")
    @PostMapping("/dismissTeam")
    public Result dismissTeam(Long tpId, HttpServletRequest request) throws ParameterException, Exception {
        if (tpId == null || tpId < 0l) {
            throw new ParameterException("tpId为空或格式错误");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        //获取uid
        Long uid = (Long) request.getAttribute("userId");
        //解散队伍
        String msg = teamProfileService.dismissTeam(tpId, uid);
        return Result.success(HttpStatus.SUCCESS, msg, null);
    }


    /*
    队伍介绍相关的增删查改
    * */
    //    @AuthorizationRequired
    @Operation(summary="根据id找队伍介绍")
    @GetMapping("/search")
    public Result getByTpId(@RequestParam("tpId") Long tpId) throws ParameterException {
        return Result.success(HttpStatus.SUCCESS,"查找成功",teamProfileService.getByTpId(tpId));
    }

    @Operation(summary="新增队伍介绍")
    @PostMapping("/add")
    public Result add(@RequestBody TeamProfile teamProfile) throws ParameterException {
        Integer rows =  teamProfileService.insertTeamProfile(teamProfile);
        return rows > 0 ? Result.success("添加队伍组成成功"):Result.error("添加队伍组成失败");
    }

    @Operation(summary="修改队伍介绍")
    @PostMapping("/edit")
    public Result edit(@RequestBody TeamProfile teamProfile,HttpServletRequest request) throws ParameterException {
        int rows = teamProfileService.updateTeamProfile(teamProfile);
        return rows > 0 ? Result.success("修改队伍组成成功"):Result.error("修改队伍组成失败");
    }


    @Operation(summary="删除队伍介绍")
    @PostMapping ("/delete")
    public Result remove(@RequestBody List<TeamProfile> teamProfiles,HttpServletRequest request) throws ParameterException {
        int row = 0;
        int length = teamProfiles.size();
        for(TeamProfile teamProfile:teamProfiles){
            row += teamProfileService.deleteTeamProfileById(teamProfile);
        }
        return row ==length ? Result.success("删除队伍组成成功") : Result.error("删除队伍组成失败");
    }

    @GetMapping("/page")
    @Operation(summary="分页搜索")
    public  Result page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize")Integer pageSize,TeamProfile teamProfile) throws ParameterException {
        List<TeamProfile> list = null;
        PageBean<TeamProfile> info = new PageBean<>();
        if(teamProfile.getTpUid()!=null || teamProfile.getTpUrealname()!=null || teamProfile.getTpTeamName()!=null || teamProfile.getTpProjectName()!= null || teamProfile.getTpRegistrationDeadline()!=null){
            list = teamProfileService.selectTeamProfileList(teamProfile);
        }else{
            list =  teamProfileService.listAllTeamProfile();
        }
        // 对查询结果进行分页处理
        PageInfo<TeamProfile> pageInfo = new PageInfo<>(list);
        int total = (int) pageInfo.getTotal();
        // 计算起始索引和结束索引
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, total);
        // 提取当前页的数据
        List<TeamProfile> pageList = list.subList(startIndex, endIndex);
        // 设置 PageBean 对象的属性
        info.setPageList(pageList);
        info.setPageNumber(pageNum);
        info.setPageSize(pageSize);
        info.setTotal(total);
        info.setTotalPage((total + pageSize - 1) / pageSize); // 计算总页数
        return Result.success(info);
    }
}
